package com.haoshuang.zhouzhoubang.ui.page.home.settings

import android.content.Context
import android.location.Location
import android.os.Bundle
import android.util.Log
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.haoshuang.zhouzhoubang.MyApp
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.databinding.ActivityStoreSettingsBinding
import com.haoshuang.zhouzhoubang.model.bean.TeamSettingsInfoBean
import com.haoshuang.zhouzhoubang.model.event.RefreshTeamUserInfo
import com.haoshuang.zhouzhoubang.ui.dialog.ConfirmDialog
import com.haoshuang.zhouzhoubang.ui.dialog.JdDialog
import com.haoshuang.zhouzhoubang.ui.page.area.ServiceAreaActivity
import com.haoshuang.zhouzhoubang.ui.page.home.settings.rate.TeamRateSetActivity
import com.haoshuang.zhouzhoubang.ui.page.home.settings.skill.add.AddSkillListActivity
import com.haoshuang.zhouzhoubang.ui.page.home.settings.skill.passed.PassedSkillListActivity
import com.haoshuang.zhouzhoubang.ui.page.home.settings.skill.record.SkillRecordActivity
import com.haoshuang.zhouzhoubang.utils.LocationUtils
import com.haoshuang.zhouzhoubang.utils.PermissionHelper
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lnkj.jialubao.utils.AccountUtils
import com.lxj.xpopup.XPopup
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.callPhone
import com.mufeng.libs.utils.ktx.convertInt
import com.mufeng.libs.utils.ktx.getString
import com.mufeng.libs.utils.ktx.toJson
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.startPageForResult
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.clickWithTrigger
import com.qw.curtain.lib.Curtain
import com.qw.curtain.lib.Curtain.CallBack
import com.qw.curtain.lib.CurtainFlow
import com.qw.curtain.lib.IGuide
import com.qw.curtain.lib.flow.CurtainFlowInterface
import com.qw.curtain.lib.shape.RoundShape

/**
 *  门店设置
 */
class StoreSettingsActivity :
    BaseVMActivity<StoreSettingsViewModel, ActivityStoreSettingsBinding>() {

    // 设置的优先接单距离
    private var acceptanceDistance = ""
    private var teamInfo: TeamSettingsInfoBean? = null

    companion object {
        fun launch(context: Context) {
            context.startPage<StoreSettingsActivity>()
        }
    }

    /**
     * 订单奖金是否分配
     */
    private var allocation = 1

    // 违约扣除 1: 门店, 2 师傅, 3 都扣
    private var dedit = 0
    var city1 = ""
    var city2 = ""
    var city3 = ""
    var city_id = ""
    override fun onDestroy() {
        super.onDestroy()
        LocationUtils.unregister()
    }

    override fun onStop() {
        LiveEventBus.get(RefreshTeamUserInfo::class.java).post(RefreshTeamUserInfo)
        super.onStop()
    }

    override fun initView(savedInstanceState: Bundle?) {
        binding.titleBar.title = "门店设置"
        binding.titleBar.leftImageView().click { finish() }

        binding.tvSkillRecord.clickWithTrigger {
            // 技能记录
            startPage<SkillRecordActivity>()
        }

        binding.tvAddSkill.clickWithTrigger {
            // 添加技能
            startPageForResult<AddSkillListActivity> { code, data ->
                if (code == 200) {
                    vm.getTeamSettingsInfo()
                }

            }
        }

        binding.clPassedSkill.clickWithTrigger {
            // 查看已经通过的技能列表
            startPage<PassedSkillListActivity>()
        }

        binding.tvChooseCity.clickWithTrigger {
            // 选择城市 服务区域
            startPageForResult<ServiceAreaActivity>(
                "city1" to city1, "city3" to city3, "city2" to city2
            ) { code, data ->
                if (code == 200 && data != null) {
                    city1 = data.getStringExtra("city1").toString()
                    city2 = data.getStringExtra("city2").toString()
                    city3 = data.getStringExtra("city3").toString()
                    city_id = data.getStringExtra("city_id").toString()
                    binding.tvChooseCity.text = city3
                    vm.updateTeamArea(city_id)
                }
            }
        }

        binding.tvChooseAddress.clickWithTrigger {
            // 选择地址 门店地址 提示联系客服修改
            XPopup.Builder(mActivity)
                .asCustom(
                    ConfirmDialog(
                        context = mActivity,
                        title = "温馨提示",
                        content = "修改门店地址, 请联系客服",
                        cancelStr = "取消",
                        confirmStr = "联系客服",
                        isHideCancel = false,
                        onCancel = {},
                        onConfirm = {
                            callPhone(MyApp.systemConfig?.tel ?: "")
                        })
                ).show()
        }
        binding.tvAcceptanceDistance.clickWithTrigger {
            // 接单距离
            XPopup.Builder(mActivity)
                .autoFocusEditText(false)
                .asCustom(JdDialog(mActivity) {
                    vm.setOrderDistance(it)
                })
                .show()
        }
        binding.tvBl.clickWithTrigger {
            // 门店比例设置
            startPageForResult<TeamRateSetActivity>(
                "team_rate" to teamInfo?.toJson(),
            ) { code, data ->
                if (code == 200 && data != null) {
                    val team_rate = data.getString("team_rate")
                    val team_leader_rate = data.getString("team_leader_rate")
                    val team_member_rate = data.getString("team_member_rate")
                    teamInfo?.team_rate = team_rate
                    teamInfo?.team_leader_rate = team_leader_rate
                    teamInfo?.team_member_rate = team_member_rate
                }
            }
        }
        binding.radioGroup.setOnCheckedChangeListener { group, checkedId ->
            // 订单奖励
            when (checkedId) {
                R.id.rbAllocation -> {
                    // 分配
                    if (allocation != 1 && binding.rbAllocation.isChecked) {
                        // 保存修改
                        allocation = 1
                        vm.setOrderAward(team_id, allocation)
                    }
                }

                R.id.rbUnAllocation -> {
                    // 不分配
                    if (allocation != 0 && binding.rbUnAllocation.isChecked) {
                        // 保存修改
                        allocation = 0
                        vm.setOrderAward(team_id, allocation)
                    }
                }
            }
        }
        binding.rgStoreDefaultDeduction.setOnCheckedChangeListener { group, checkedId ->
            // 违约扣除
            when (checkedId) {
                R.id.rbTeam -> {
                    // 门店
                    if (dedit != 1 && binding.rbTeam.isChecked) {
                        // 保存修改
                        dedit = 1
                        vm.setOrderDedit(dedit)
                    }
                }

                R.id.rbMember -> {
                    // 师傅
                    if (dedit != 2 && binding.rbMember.isChecked) {
                        // 保存修改
                        dedit = 2
                        vm.setOrderDedit(dedit)
                    }
                }

                R.id.rbAll -> {
                    // 都扣
                    if (dedit != 3 && binding.rbAll.isChecked) {
                        // 保存修改
                        dedit = 3
                        vm.setOrderDedit(dedit)
                    }
                }
            }
        }

        binding.tvRewardOrder.clickWithTrigger {
            XPopup.Builder(mActivity)
                .asCustom(
                    ConfirmDialog(
                        context = mActivity,
                        title = "订单奖励",
                        content = "订单奖励是平台设置的服务奖励\n是否将门店订单奖励平分给队员",
                        cancelStr = "",
                        confirmStr = "我知道了",
                        isHideCancel = true,
                        onCancel = {},
                        onConfirm = {})
                )
                .show()
        }

        binding.tvStoreDefaultDeduction.clickWithTrigger {
            XPopup.Builder(mActivity)
                .asCustom(
                    ConfirmDialog(
                        context = mActivity,
                        title = "门店违约扣除",
                        content = "指的是订单违约时扣除金额将从哪一方扣除。",
                        cancelStr = "",
                        confirmStr = "我知道了",
                        isHideCancel = true,
                        onCancel = {},
                        onConfirm = {})
                )
                .show()
        }

        if (!AccountUtils.teamSetGuide) {
            showGuide()
        }
    }

    private fun showGuide(){
        CurtainFlow.Builder()
            .with(1, getStepOneGuide())
            .with(2, getStepTwoGuide())
            .with(3, getStepThreeGuide())
            .create()
            .start(object : CurtainFlow.CallBack{
                override fun onProcess(currentId: Int, curtainFlow: CurtainFlowInterface?) {
                    when(currentId){
                        1 -> {
                            curtainFlow?.findViewInCurrentCurtain<TextView>(R.id.tvNext)
                                ?.click {
                                    curtainFlow.toCurtainById(2)
                                }
                            binding.llGuile1.post {
                                val bottom = binding.llGuile1.bottom
                                val lp = curtainFlow?.findViewInCurrentCurtain<ImageView>(R.id.ivArrow)?.layoutParams as LinearLayout.LayoutParams?
                                lp?.setMargins(0,bottom,0,0)
                                curtainFlow?.findViewInCurrentCurtain<ImageView>(R.id.ivArrow)?.layoutParams = lp
                            }
                        }
                        2 -> {
                            curtainFlow?.findViewInCurrentCurtain<TextView>(R.id.tvNext)
                                ?.click {
                                    curtainFlow.toCurtainById(3)
                                }
                            binding.llLin2.post {
                                val bottom = binding.llLin2.bottom
                                val lp = curtainFlow?.findViewInCurrentCurtain<ImageView>(R.id.ivArrow)?.layoutParams as LinearLayout.LayoutParams?
                                lp?.setMargins(0,bottom,0,0)
                                curtainFlow?.findViewInCurrentCurtain<ImageView>(R.id.ivArrow)?.layoutParams = lp
                            }
                        }
                        3 -> {
                            curtainFlow?.findViewInCurrentCurtain<TextView>(R.id.tvNext)
                                ?.click {
                                    AccountUtils.teamSetGuide = true
                                    curtainFlow.finish()
                                }
                            binding.tvBl.post {
                                val bottom = binding.tvBl.bottom
                                val top = binding.llGuide3.top
                                val lp = curtainFlow?.findViewInCurrentCurtain<ImageView>(R.id.ivArrow)?.layoutParams as LinearLayout.LayoutParams?
                                lp?.setMargins(0,top+bottom,0,0)
                                curtainFlow?.findViewInCurrentCurtain<ImageView>(R.id.ivArrow)?.layoutParams = lp
                            }
                        }
                    }
                }

                override fun onFinish() {

                }
            })

    }

    private fun getStepOneGuide(): Curtain {
        return Curtain(mActivity)
            .with(binding.llGuile1)
            .withShape(binding.llGuile1, RoundShape(12f))
            .setTopView(R.layout.guide_team_set1)
    }

    private fun getStepTwoGuide(): Curtain {
        return Curtain(mActivity)
            .with(binding.llLin2)
            .withShape(binding.llLin2, RoundShape(12f))
            .setTopView(R.layout.guide_team_set2)

    }

    private fun getStepThreeGuide(): Curtain {
        return Curtain(mActivity)
            .with(binding.tvBl)
            .withShape(binding.tvBl, RoundShape(12f))
            .setTopView(R.layout.guide_team_set3)
    }

    override fun initData() {
        vm.getTeamSettingsInfo()
    }

    override fun startObserve() {

        // 优先接单距离
        vm.setOrderDistanceData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                toast("提交成功, 等待客服审核")
            }
        }

        // 订单奖励
        vm.setOrderAwardData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
            }
        }

        // 违约扣除
        vm.setOrderDeditData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
            }
        }
        // 门店设置信息
        vm.getTeamSettingsInfoData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                teamInfo = it?.data
                setupTeamInfo()
            }
        }
    }

    private fun setupTeamInfo() {
        if (teamInfo == null) {
            return
        }
        binding.apply {
            tvSkillNum.text = "我选择的类别(已选择${teamInfo?.all_cate_count}类)"
            tvChoosedSkillNum.text = teamInfo?.cate_count.toString()
            tvChooseCity.text = "${teamInfo?.area_name?.joinToString()}"
            tvChooseAddress.text = "${teamInfo?.team_address}"
            tvAcceptanceDistance.text = if (teamInfo?.order_distance == "0") "无限制" else "${teamInfo?.order_distance}km"
            allocation = teamInfo?.order_award ?: 0
            dedit = teamInfo?.order_dedit.convertInt(0)
            rbAllocation.isChecked = teamInfo?.order_award == 1
            rbUnAllocation.isChecked = teamInfo?.order_award != 1
            rbTeam.isChecked = teamInfo?.order_dedit == "1"
            rbMember.isChecked = teamInfo?.order_dedit == "2"
            rbAll.isChecked = teamInfo?.order_dedit == "3"
            city1 = teamInfo?.province_name ?: ""
            city2 = teamInfo?.city_name ?: ""
            city3 = teamInfo?.area_name?.joinToString(",") ?: ""
        }

    }

}